import axios from 'axios'
import VueRouter from '@/router'
import { Toast } from 'vant'
// import store from '@/store'
// import { getToken } from '@/utils/auth'


// create an axios instance
const service = axios.create({
    baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
    // withCredentials: true, // send cookies when cross-domain requests
    timeout: 10000 // request timeout
})

// request interceptor
service.interceptors.request.use(
    config => {
        // 设置token
        let __token = localStorage.getItem('token')
        if (__token) {
            config.headers['__token'] = __token
        }
        return config
    },
    error => {
        console.log(error) // for debug
        return Promise.reject(error)
    }
)

// response interceptor
service.interceptors.response.use(
    async(response) => {
        const res = response.data
        if (res.code !== 1) {
            if (res.code !== -1) {
                Toast({
                    message: res.msg || 'Error',
                    type: 'fail',
                    duration: 2 * 1000
                })
            }
            if (res.code === -1 && localStorage.getItem("isAuth")) {
                localStorage.setItem("token", "");
                localStorage.setItem("userInfo", "");
                localStorage.setItem("isAuth", "");
                window.location.reload()
                return null
            }
        }
        return res.data || res
    },
    error => {
        console.log('err' + error) // for debug
        Toast({
            message: error.msg,
            type: 'fail',
            duration: 2 * 1000
        })
        return Promise.reject(error)
    }
)

export default service